<?php
namespace app\pet\controller;
use think\Db;

Class Codeexport extends Common{

    public function index(){

        return $this->fetch();
    }

    public function excelSub(){
        $params = $this->params;
        $filename = $params['filename'];
        $filename = ROOT_PATH . $filename;
        \think\Loader::import('PHPExcel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        \think\Loader::import('PHPExcel.IOFactory.PHPExcel_IOFactory');
        $extension = strtolower( pathinfo($filename, PATHINFO_EXTENSION) );
        if ($extension =='xlsx') {
            $objReader = new \PHPExcel_Reader_Excel2007();
            $objExcel = $objReader ->load($filename);

        } else if ($extension =='xls') {

            $objReader = new \PHPExcel_Reader_Excel5();
            $objExcel = $objReader->load($filename);
        }
        else{
            return_msg(0,'请导入xls或xlsx文件！');
        }

        \think\Loader::import('PHPExcel.IOFactory.PHPExcel_IOFactory');
        if ($extension =='xlsx') {
            $objReader = new \PHPExcel_Reader_Excel2007();
            $objExcel = $objReader ->load($filename);
        } else if ($extension =='xls') {
            $objReader = new \PHPExcel_Reader_Excel5();
            $objExcel = $objReader->load($filename);
        }

        $excel_array=$objExcel->getsheet(0)->toArray();   //转换为数组格式

        $arr =[];
        foreach ($excel_array as $k=>$v){
            if($v[0]!='激活码'){
                array_push($arr,$v[0]);
            }
        }
        $search = Db::name('activation_code')->whereIn('activation_code',$arr)->select();
        foreach ($arr as $k=>$v){
            foreach ($search as $k1=>$v1){
                if($v==$v1['activation_code']){
                    unset($arr[$k]);
                }
            }
        }
        $inserArr = [];
        foreach ($arr as $k=>$v){
            array_push($inserArr,['activation_code'=>$v]);
        }
        $res = Db::name('activation_code')->insertAll($inserArr);
        if($res){
            return_msg(1,'导入成功！',[],'/pet/home/index');
        }
        else{
            return_msg(0,'导入失败！');
        }
    }


}